package com.dacool.dialog;

import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.dacool.util.ViewUtils;

public class BasePickerDialog extends BaseDialog {

	private int selectedIndex;

	public BasePickerDialog setSelectedIndex(int selectedIndex) {
		this.selectedIndex = selectedIndex;
		return this;
	}

	public static interface PickerDialogDelegate {
		public void didCancel();

		public void selectedItemAtIndex(int index);
	}

	public BasePickerDialog(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	protected ListView lv;

	protected PickerDialogDelegate delegate;

	public BasePickerDialog setDelegate(PickerDialogDelegate delegate) {
		this.delegate = delegate;
		return this;
	}

	private BaseAdapter mAdapter;

	public void setAdapter(BaseAdapter mAdapter) {
		this.mAdapter = mAdapter;
		if (lv != null) {
			lv.setAdapter(mAdapter);
		}
	}
	
	protected BaseAdapter getAdapter(){
		return this.mAdapter;
	}

	public PickerDialogDelegate getDelegate() {
		return delegate;
	}

	@Override
	protected View myView() {
		if (lv != null)
			return lv;
		lv = new ListView(getContext());
		lv.setPadding(ViewUtils.rp(10), ViewUtils.rp(5), ViewUtils.rp(10),
				ViewUtils.rp(5));
		if (mAdapter != null)
			lv.setAdapter(mAdapter);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (BasePickerDialog.this.delegate != null) {
					BasePickerDialog.this.delegate
							.selectedItemAtIndex(position);
				}
				BasePickerDialog.this.dismiss();
			}
		});
		this.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				if (BasePickerDialog.this.delegate != null)
					BasePickerDialog.this.delegate.didCancel();
			}
		});
		return lv;
	}

	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();
		lv.setSelection(selectedIndex);
	}

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return 0;
	}

}
